package com.cc.web.admin;

import com.cc.po.User;
import com.cc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

/**
 * Created by zcc on 2020/12/17.
 */
@Controller
@RequestMapping("/admin")
public class LoginController {

 //注入userservice对象
    @Autowired
    private UserService userService;
//跳转到登陆页面方法
    @GetMapping
    public String loginPage() {
        return "admin/login";
    }

//登陆方法
    @PostMapping("/login")
    public String login(@RequestParam String username,//获取请求的参数数据
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes) {
        User user = userService.checkUser(username, password);
        if (user != null) {
            //注意不能将密码也传送过去
            user.setPassword(null);
            //若用户名和密码不为空，则将数据保存到session中
            session.setAttribute("user",user);

            return "admin/index";
        } else {
            //密码错误则重定向到登录页面并返回错误信息
            attributes.addFlashAttribute("message", "用户名或密码错误");
            return "redirect:/admin";
        }
    }
//登出方法
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        //登出则移除session域中的数据，并重定向到登录页面
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
